// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.ui.web;

import java.util.ArrayList;
import java.util.List;

import org.dengues.ui.web.browser.DenguesBrowser;
import org.dengues.ui.web.browser.dom.HTMLDocument;
import org.dengues.ui.web.browser.event.DenguesProgressEvent;
import org.dengues.ui.web.browser.event.DenguesProgressListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.internal.browser.BusyIndicator;
import org.eclipse.ui.internal.browser.ImageResource;
import org.eclipse.ui.internal.browser.Messages;
import org.eclipse.ui.internal.browser.ToolbarLayout;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 1 2006-09-29 17:06:40Z qiang.zhang $
 * 
 */
public class HTMLBrowserComposite extends Composite {

    private final String url;

    private DenguesBrowser browser;

    private HTMLStructureComposite structureComposite;

    protected ToolItem back;

    protected ToolItem forward;

    public Combo combo;

    protected BusyIndicator busy;

    protected static List<String> history = new ArrayList<String>();

    /**
     * Qiang.Zhang.Adolf@gmail.com HTMLBrowserComposite constructor comment.
     * 
     * @param parent
     * @param url
     */
    public HTMLBrowserComposite(Composite parent, String url) {
        super(parent, SWT.BORDER);
        this.url = url;
        setBackground(parent.getBackground());
        GridLayout gridLayout = new GridLayout();
        gridLayout.marginBottom = 0;
        gridLayout.marginWidth = 0;
        gridLayout.marginTop = 0;
        gridLayout.marginRight = 0;
        gridLayout.marginLeft = 0;
        gridLayout.marginHeight = 0;

        setLayout(gridLayout);

        GridData gridData = new GridData(GridData.FILL_BOTH);
        setLayoutData(gridData);
        Composite toolbarComp = new Composite(this, SWT.NONE);
        toolbarComp.setLayout(new ToolbarLayout());
        toolbarComp.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL));
        createToolbar(toolbarComp);
        createLocationBar(toolbarComp);
        busy = new BusyIndicator(toolbarComp, SWT.NONE);
        busy.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
        createBrowserViewer();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createBrowserViewer".
     */
    private void createBrowserViewer() {
        browser = new DenguesBrowser(this);
        if (url != null) {
            busy.setBusy(true);
            browser.navigate(url);
            combo.setText(url);
            updateHistory();
            browser.addProgressListener(new DenguesProgressListener() {

                /*
                 * (non-Javadoc)
                 * 
                 * @see org.dengues.ui.web.browser.event.DenguesProgressListener#changed(org.dengues.ui.web.browser.event.DenguesProgressEvent)
                 */
                public void changed(DenguesProgressEvent event) {

                }

                /*
                 * (non-Javadoc)
                 * 
                 * @see org.dengues.ui.web.browser.event.DenguesProgressListener#completed(org.dengues.ui.web.browser.event.DenguesProgressEvent)
                 */
                public void completed(DenguesProgressEvent event) {
                    HTMLDocument document = browser.getDocument();
                    // NodeList childNodes = document.getAll();
                    // System.out.println(document.getNodeName());
                    // System.out.println(childNodes);
                    // int length = childNodes.getLength();
                    // System.out.println(length);
                    // for (int i = 0; i < length; i++) {
                    // Node item = childNodes.item(i);
                    // System.out.println(i + " Item " + item.getNodeName());
                    // }
                    structureComposite.setInput(document);
                    busy.setBusy(false);
                }

            });
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "setHTMLStructureComposite".
     * 
     * @param structureComposite
     */
    public void setHTMLStructureComposite(HTMLStructureComposite structureComposite) {
        this.structureComposite = structureComposite;
    }

    private ToolBar createToolbar(Composite parent) {
        ToolBar toolbar = new ToolBar(parent, SWT.FLAT);

        // create refresh, stop, and print actions
        ToolItem stop = new ToolItem(toolbar, SWT.NONE);
        stop.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_STOP));
        stop.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_STOP));
        stop.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_STOP));
        stop.setToolTipText(Messages.actionWebBrowserStop);
        stop.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent event) {
                stop();
            }
        });

        ToolItem refresh = new ToolItem(toolbar, SWT.NONE);
        refresh.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_REFRESH));
        refresh.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_REFRESH));
        refresh.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_REFRESH));
        refresh.setToolTipText(Messages.actionWebBrowserRefresh);
        refresh.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent event) {
                refresh();
            }
        });

        return toolbar;
    }

    /**
     * Refresh the current page. Convenience method that calls the underlying SWT browser.
     * 
     * @exception SWTException
     * <ul>
     * <li>ERROR_THREAD_INVALID_ACCESS when called from the wrong thread</li>
     * <li>ERROR_WIDGET_DISPOSED when the widget has been disposed</li>
     * </ul>
     */
    public void refresh() {
        if (browser != null) {
            busy.setBusy(true);
            browser.refresh();
        } else {
            // text.refresh();
        }
        try {
            Thread.sleep(50);
        } catch (Exception e) {
            // ignore
        }
    }

    /**
     * Stop any loading and rendering activity. Convenience method that calls the underlying SWT browser.
     * 
     * @exception SWTException
     * <ul>
     * <li>ERROR_THREAD_INVALID_ACCESS when called from the wrong thread</li>
     * <li>ERROR_WIDGET_DISPOSED when the widget has been disposed</li>
     * </ul>
     */
    public void stop() {
        if (browser != null)
            browser.stop();
    }

    private ToolBar createLocationBar(Composite parent) {
        combo = new Combo(parent, SWT.DROP_DOWN);

        combo.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent we) {
                try {
                    if (combo.getSelectionIndex() != -1) {
                        busy.setBusy(true);
                        browser.navigate(combo.getItem(combo.getSelectionIndex()));
                    }
                } catch (Exception e) {
                    // ignore
                }
            }
        });
        combo.addListener(SWT.DefaultSelection, new Listener() {

            public void handleEvent(Event e) {
                busy.setBusy(true);
                browser.navigate(combo.getText());
            }
        });

        ToolBar toolbar = new ToolBar(parent, SWT.FLAT);

        ToolItem go = new ToolItem(toolbar, SWT.NONE);
        go.setImage(ImageResource.getImage(ImageResource.IMG_ELCL_NAV_GO));
        go.setHotImage(ImageResource.getImage(ImageResource.IMG_CLCL_NAV_GO));
        go.setDisabledImage(ImageResource.getImage(ImageResource.IMG_DLCL_NAV_GO));
        go.setToolTipText(Messages.actionWebBrowserGo);
        go.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent event) {
                busy.setBusy(true);
                browser.navigate(combo.getText());
                updateHistory();
            }
        });

        return toolbar;
    }

    /**
     * Update the history list to the global/shared copy.
     */
    protected void updateHistory() {
        if (combo == null)
            return;

        String temp = combo.getText();
        history.add(temp);
        String[] historyList = new String[history.size()];
        history.toArray(historyList);
        combo.setItems(historyList);

        combo.setText(temp);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getURL".
     * 
     * @return
     */
    public String getURL() {
        return combo.getText();
    }
}
